import random
import re

from django.shortcuts import render
from django.views import View

# Create your views here.
from meiduo_mall.libs.captcha.captcha import captcha
from django import http
from django_redis import get_redis_connection

from meiduo_mall.libs.yuntongxun.sms import CCP
from meiduo_mall.utils.constants import *
from meiduo_mall.utils.response_code import RET


class ImageCodeView(View):

    def get(self, request, uuid):
        # 1, 获取图片验证码, 图片
        _, text, image_data = captcha.generate_captcha()
        # 2, 存储图片验证码的值到redis中
        redis_conn = get_redis_connection('code')
        redis_conn.set('image_code_%s' % uuid, text, REDIS_IMAGE_CODE_EXPIRES)
        print(text)
        return http.HttpResponse(image_data, content_type='image/png')


class SMSCodeView(View):

    def get(self, request, mobile):
        redis_conn = get_redis_connection('code')
        pipeline = redis_conn.pipeline()
        # 1,获取参数
        image_code = request.GET.get("image_code")
        image_code_id = request.GET.get("image_code_id")

        # 判断 一分钟之内是否多次发送短信
        send_flag = redis_conn.get('send_flag_%s' % mobile)
        if send_flag:
            return http.JsonResponse({'code': RET.DBERR, 'errmsg': '短信多次发送'})

        # 2，校验参数
        # 2.1 为空校验
        if not all([image_code, image_code_id]):
            return http.JsonResponse({'code': RET.DBERR, 'errmsg': '参数不全'}, safe=True, json_dumps_params={'ensure_ascii': False})

        print(image_code, image_code_id)
        # 2.1 手机格式校验
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'code': RET.DBERR, 'errmsg': '手机格式错误'}, safe=True, json_dumps_params={'ensure_ascii': False})

        redis_image_code = redis_conn.get('image_code_%s' % image_code_id)

        if not redis_image_code:
            return http.JsonResponse({'code': RET.DBERR, 'errmsg': '图片验证码已过期'})

        if image_code.upper() != redis_image_code.decode().upper():
            return http.JsonResponse({'code': RET.DBERR, 'errmsg': '图片验证码错误'})

        sms_code = "%06d" % random.randint(0, 999999)
        print(f'sms_code={sms_code}')

        from celery_tasks.sms.task import send_message
        send_message.delay(mobile, sms_code)
        # ccp = CCP()
        # 注意： 测试的短信模板编号为1s
        # 【云通讯】您使用的是云通讯短信模板，您的验证码是 123456，请于5分钟内正确输入
        # result = ccp.send_template_sms(mobile, [sms_code, 5], 1)

        # if result == -1:
        pipeline.set('sms_code_%s' % mobile, sms_code, REDIS_SMS_CODE_EXPIRES)
        # 1分钟之内只能发送1次短信
        pipeline.set('send_flag_%s' % mobile, 1, REDIS_SEND_FLAG_EXPIRES)
        print("发送成功 %s" % sms_code)
        pipeline.execute()
        return http.JsonResponse({'code': RET.DBERR, 'errmsg': f'验证码是{sms_code}'})
        # else:
        #     return http.JsonResponse({'code': 400, 'errmsg': '发送失败'})


